<template>
    <div :class="{'dark':state == 'dark'}" :style="{width: '100%', height: '100%'}">
        <div class="echart" :id="`eyeChart-${props.elKey}`"></div>
        <div class="sampleRate">
            <pui-color-picker class="selectColor" @changeColor="selectColor"></pui-color-picker>
            <div class="form-item">
                <input class="pui-input" type="number" min="0.1" max="1" v-model="rate" step="0.1" placeholder="采样率(0~1)">
                <pui-button @click="changeRate">确定</pui-button>
            </div>
        </div>
    </div> 
</template>

<script lang="ts">
import { defineComponent} from 'vue'
export default defineComponent({
    name: 'EyeDiagram',
})
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, getCurrentInstance} from 'vue'
import * as echarts from 'echarts'
import jsPDF from 'jspdf';
import getMyMixin from './myMixin';
import { sampleArrayByRateForCharts } from '@/utils'
const { proxy }: any = getCurrentInstance()
onMounted(() => {
    console.log(proxy.$loading)
    initEcharts();
});
const props = defineProps({
    elKey: {
        type: Number,
        default: 0
    }
})
const dcolor = ref('#569ff8')
const state = ref('')
const rate = ref(0.1)
const oldRate = ref(0.1)
let url = ''
var option = {} as any
const Mixin = getMyMixin("")
const chartsData: any = ref(null)
const initEcharts = async (e?: any) => {
    await nextTick()
    if (e && e.opts && e.opts.data) {
        const myChart = echarts.init(document.getElementById(`eyeChart-${props.elKey}`) as HTMLElement);
        option = {
            xAxis: [
                {
                    splitLine:{
                        show:true
                    },
                    axisTick: {
                        alignWithLabel: true, // 刻度线和标签对齐。
                    },
                    axisLine: {
                        onZero: false,    //有负数x轴下落至y轴最小值
                    },
                },
                {
                    alignTicks: true,
                    splitLine:{
                        show:true
                    },
                    axisTick: {
                        alignWithLabel: true, // 刻度线和标签对齐。
                    },
                    axisLine: {
                        onZero: false,    //有负数x轴下落至y轴最小值
                    },
                    name: 'Eye diagram',
                    nameLocation: 'center',
                    nameTextStyle:{
                        padding: [0, 0, 10, 0], // 可以调整标题距离坐标轴的距离 [上，右，下，左]
                    },
                }
            ],
            yAxis: [
                {
                    axisLine:{
                        show:true,
                        onZero:false,
                    },
                    splitLine:{
                        show:true //显示网格线
                    },
                },
                {
                    alignTicks: true,
                    axisLine:{
                        show:true,
                        onZero:false,
                    },
                    splitLine:{
                        show:true //显示网格线
                    },
                }
            ],
            series: [],
            toolbox: {
                right: 10,
                feature: {
                    dataZoom: {
                        show:true,
                    }
                }
            },
            grid: {
                top: '12%',
            },
            tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                trigger: 'axis',
                backgroundColor: 'rgba(32, 33, 36,.7)',
                showContent:true, //显示数据值
                borderColor: 'rgba(32, 33, 36,0.20)',
                borderWidth: 1,
                textStyle: { // 文字提示样式
                    color: '#fff',
                    fontSize: '12'
                },
                axisPointer: { // 坐标轴虚线
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                },
            },  
        };
        chartsData.value = e.opts.data
        let temp: any[] = sampleArrayByRateForCharts(chartsData.value.signal.complexDoubleArray, e.sampleRate)
        option.series.push(
            {
                data:temp,
                type:"line",
                itemStyle:{
                    normal:{
                        lineStyle:{
                            width:0.08
                        }
                    }
                },
                color:dcolor.value,
                smooth:true,
                symbol: "none", 
                large: true,
                yAxisIndex: 0,
                xAxisIndex: 0,
            },
            {
                tooltip: {
                    show: false
                },
                data:temp,
                type:"line",
                itemStyle:{
                    normal:{
                        lineStyle:{
                            width:0.08
                        }
                    }
                },
                visible: false,
                color:dcolor.value,
                smooth:true,
                symbol: "none", 
                large: true,
                yAxisIndex: 1,
                xAxisIndex: 1,
            },
        )
        myChart.clear();
        myChart.setOption(option,true);
        myChart.resize()
        myChart.dispatchAction({
            type:'takeGlobalCursor',
            key:'dataZoomSelect',
            dataZoomSelectActive:true
        })
        window.addEventListener("resize", function () {
            myChart.resize();
        });
        url = getImgUrl()
    }
}
const changeState = (val: any) => {
    state.value = val
}
const selectColor = async (value:any) =>{
    dcolor.value = value
    await initEcharts({data: chartsData.value})
}
const readFile = (filePath: any) => {
    let xhr = null, 
    okStatus = document.location.protocol === 'file' ? 0 : 200
        xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
        xhr.open('GET', filePath, false)
        xhr.overrideMimeType('text/html;charset=utf-8')
        xhr.send(null)
        return xhr.status === okStatus ? xhr.responseText : null
}
const saveCSV = () => {
    let content = dataToCSV();
    Mixin.saveCSV("eyeDiagram",content)
}
const dataToCSV = () => {
    let csv = '';
    for(let i in option.series){
        for(let j in option.series[i].data){
            csv += option.series[i].data[j][1] + ',';
        }
        csv += '\r\n';
    }
    let content = new Blob(['\uFEFF' + csv]);
    return content;
}
const getImgUrl = () => {
    let url = Mixin.getImgUrl(`eyeChart-${props.elKey}`)
    return url
}
const saveimg = async () => {
    await nextTick()
    Mixin.saveImg('eyeDiagram',url)
}
const savePDF = async () => {
    await nextTick()
    var doc = new jsPDF('l', 'pt', 'letter')
    doc.addImage(url, 100, 5, 590, 590, 'img')
    doc.save('eyeDiagram')
}
const reload = () => {
    const myChart = echarts.init(document.getElementById(`eyeChart-${props.elKey}`) as HTMLElement);
    myChart.resize()
}
const init = async (e: any, sampleRate: any = 0.1) => {
    rate.value = sampleRate
    oldRate.value = sampleRate
    await initEcharts({data: e, sampleRate})
}
const changeRate = async () => {
    if (oldRate.value === rate.value) return
    proxy.$loading.open('正在绘制图表...')
    oldRate.value = rate.value
    await initEcharts({data: chartsData.value, sampleRate: rate.value})
    setTimeout(() => {
        proxy.$loading.close()
    }, 700)
}
defineExpose({
    saveCSV,
    dataToCSV,
    getImgUrl,
    saveimg,
    savePDF,
    selectColor,
    initEcharts,
    reload,
    changeState,
    changeRate,
    init
})
</script>

<style lang="scss" scoped>
.echart{
    text-align: center;
    margin:auto;
    // position:absolute;
    // padding-right: 20%;
    // padding-top: 10%;
    // padding-left: 10%;
    // top:0;
    // left: 0;
    // right:0;
    // bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    box-sizing: border-box;
    position: relative;
}
.sampleRate{
    position: absolute;
    top: 10px;
    left: 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .form-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-left: 20px;
        .label {
            font-size: 12px;
            padding-right: 5px;
        }
        .pui-input {
            width: 80px;
            margin-right: 10px;
            outline: none;
            font-size: 12px;
        }
    }
    .pui-btn {
        padding: 5px 10px;
    }
}
.dark{
    background-color: black;
}
</style>